interface TipsObject extends egret.DisplayObject {
	tips: string;
}

class MainTips extends UILayer {
	Main: egret.DisplayObject;

	constructor(Main: egret.DisplayObject) {
		super();
		Main.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBeginMain, this);
		Main.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEndMain, this);

		Main.addEventListener(mouse.MouseEvent.MOUSE_OVER, this.onMouseOverMain, this);
		Main.addEventListener(mouse.MouseEvent.MOUSE_OUT, this.onMouseOutMain, this);
	}

	tips: CommonTips;

	private onTouchBeginMain(e: egret.TouchEvent): void {
		const { tips } = e.target;
		if (tips && typeof tips != null) {
			let data: TipsStruct;
			if (typeof tips === 'string') {
				data = { name: '', desc: tips };
			} else if (typeof tips === 'object') {
				data = tips;
			} else if (typeof tips === 'function') {
				data = e.target.tips();
			}
			if (data) {
				this.showTips(e, data);
			}
		}
	}

	async onMouseOverMain(e: egret.TouchEvent): Promise<void> {
		if (this.tips === e.target) {
			return;
		}
		this.clearTips();
		this.onTouchBeginMain(e);
	}

	onMouseOutMain(e: egret.TouchEvent): void {
		this.clearTips();
	}

	private showTips(e: egret.TouchEvent, data: TipsStruct): void {
		const tips = CommonTips.ins();
		this.addChild(tips);
		tips.setData(data);
		const pos = new egret.Point();
		this.globalToLocal(e.stageX, e.stageY, pos);
		tips.setPos(pos.x, pos.y, this.width, this.height);
		this.tips = tips;
	}

	private onTouchEndMain(e: egret.TouchEvent): void {
		this.clearTips();
	}

	clearTips(): void {
		if (this.tips) {
			this.removeChild(this.tips);
			this.tips = null;
		}
	}
}

function setTips(ui: egret.DisplayObject, tips: any): void {
	(ui as any).tips = tips;
}
